//图标侧边栏
let searchForm = document.querySelector('.search-form');
let heart = document.querySelector('.heart');
let cart = document.querySelector('.shopping-cart');
let login = document.querySelector('.login-form');

document.querySelector('#search-btn').onclick = () => {
    searchForm.classList.toggle('active');
    heart.classList.remove('active');
    cart.classList.remove('active');
    login.classList.remove('active');
}

document.querySelector('#heart-btn').onclick = () => {
    heart.classList.toggle('active');
    cart.classList.remove('active');
    login.classList.remove('active');
    searchForm.classList.remove('active');
}

document.querySelector('#shop-btn').onclick = () => {
    cart.classList.toggle('active');
    heart.classList.remove('active');
    login.classList.remove('active');
    searchForm.classList.remove('active');
}

document.querySelector('#login-btn').onclick = () => {
    login.classList.toggle('active');
    heart.classList.remove('active');
    cart.classList.remove('active');
    searchForm.classList.remove('active');
}




//轮播
let slides = document.querySelectorAll('.home .slides-container .slide');
let index = 0;

function next() {
    slides[index].classList.remove('active');
    index = (index + 1) % slides.length;
    slides[index].classList.add('active');
}

function prev() {
    slides[index].classList.remove('active');
    index = (index - 1 + slides.length) % slides.length;
    slides[index].classList.add('active');
}


//联系我们
document.addEventListener('DOMContentLoaded', function () {
    const contactForm = document.querySelector('.contact .row form');

    // 表单提交事件监听
    contactForm.addEventListener('submit', function (event) {
        event.preventDefault(); // 阻止默认的表单提交行为

        // 获取表单元素
        const nameInput = contactForm.querySelector('input[type="text"]');
        const emailInput = contactForm.querySelector('input[type="email"]');
        const phoneInput = contactForm.querySelector('input[type="number"]');
        const messageTextarea = contactForm.querySelector('textarea');

        // 简单的表单验证
        if (!validateField(nameInput)) return;
        if (!validateEmail(emailInput)) return;
        if (!validateField(phoneInput)) return;
        if (!validateField(messageTextarea)) return;

        // 模拟表单提交
        simulateFormSubmission(contactForm);
    });
});

// 字段验证函数
function validateField(field) {
    if (field.value.trim() === '') {
        alert(`${field.placeholder}不能为空`);
        field.focus();
        return false;
    }
    return true;
}

// 邮箱验证函数
function validateEmail(emailField) {
    const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!emailPattern.test(emailField.value)) {
        alert('请输入有效的电子邮件地址');
        emailField.focus();
        return false;
    }
    return true;
}

// 模拟表单提交函数
function simulateFormSubmission(form) {
    // 模拟网络请求延迟
    setTimeout(() => {
        alert('感谢您的留言，我们将尽快回复您！');
        form.reset(); // 清空表单
    }, 1000); // 1秒延迟
}


// 收藏功能
document.querySelectorAll('.products .box .icons .fas.fa-heart').forEach(heartIcon => {
    heartIcon.addEventListener('click', function () {
        const productId = this.getAttribute('data-product-id');
        const productBox = this.closest('.box');
        const productName = productBox.querySelector('.content h3').innerText;
        const productPrice = productBox.querySelector('.content .price').innerText;
        const productImage = productBox.querySelector('.image img').src;

        // 创建新的收藏项
        const heartBox = document.createElement('div');
        heartBox.classList.add('box');

        heartBox.innerHTML = `
            <i class="fas fa-times cancel-btn"></i> <!-- 取消按钮 -->
            <img src="${productImage}" alt="">
            <div class="content">
                <h3>${productName}</h3>
                <span class="price">${productPrice}</span>
            </div>
        `;

        // 将新的收藏项添加到.heart容器中
        document.querySelector('.heart').appendChild(heartBox);

        // 更新收藏总数
        updateHeartTotal();

        // 保存收藏项到localStorage
        saveHeartItem(productId, { name: productName, price: productPrice, image: productImage });

        // 为取消按钮添加事件监听器
        const cancelButton = heartBox.querySelector('.cancel-btn');
        cancelButton.addEventListener('click', function () {
            heartBox.remove(); // 移除收藏项
            updateHeartTotal(); // 更新收藏总数
            removeHeartItem(productId); // 从localStorage中移除收藏项
        });
    });
});


function updateHeartTotal() {
    const heartBoxes = document.querySelectorAll('.heart .box');
    const totalElement = document.querySelector('.heart .total span');
    totalElement.textContent = `共${heartBoxes.length}项`;
}

function saveHeartItem(productId, productInfo) {
    let heartItems = JSON.parse(localStorage.getItem('heartItems')) || {};
    heartItems[productId] = productInfo;
    localStorage.setItem('heartItems', JSON.stringify(heartItems));
}

function removeHeartItem(productId) {
    let heartItems = JSON.parse(localStorage.getItem('heartItems')) || {};
    delete heartItems[productId];
    localStorage.setItem('heartItems', JSON.stringify(heartItems));
}

//购物功能
document.querySelectorAll('.products .box .icons .fas.fa-shopping-cart').forEach(cartIcon => {
    cartIcon.addEventListener('click', function () {
        const productId = this.getAttribute('data-product-id');
        const productBox = this.closest('.box');
        const productName = productBox.querySelector('.content h3').innerText;
        const productPrice = productBox.querySelector('.content .price').innerText;
        const productImage = productBox.querySelector('.image img').src;

        // 创建新的购物车项
        const cartBox = document.createElement('div');
        cartBox.classList.add('box');

        cartBox.innerHTML = `
            <span class="fas fa-times cancel-btn"></span> <!-- 取消按钮 -->
            <img src="${productImage}" alt="">
            <div class="content">
                <h3>${productName}</h3>
                <span class="quantity">1</span>
                <span class="multiply">×</span>
                <span class="price">${productPrice}</span>
            </div>
        `;

        // 将新的购物车项添加到.shopping-cart容器中
        document.querySelector('.shopping-cart').appendChild(cartBox);

        // 更新购物车总额
        updateCartTotal();

        // 保存购物车项到localStorage
        saveCartItem(productId, { name: productName, price: productPrice, image: productImage, quantity: 1 });

        // 为取消按钮添加事件监听器
        const cancelButton = cartBox.querySelector('.cancel-btn');
        cancelButton.addEventListener('click', function () {
            cartBox.remove(); // 移除购物车项
            updateCartTotal(); // 更新购物车总数
            removeCartItem(productId); // 从localStorage中移除购物车项
        });
    });
});

function updateCartTotal() {
    const cartBoxes = document.querySelectorAll('.shopping-cart .box');
    const totalElement = document.querySelector('.shopping-cart .total span');
    let total = 0;
    cartBoxes.forEach(box => {
        const price = parseFloat(box.querySelector('.price').innerText.replace('$', ''));
        const quantity = parseInt(box.querySelector('.quantity').innerText);
        total += price * quantity;
    });
    totalElement.textContent = `共${cartBoxes.length}项, 总计: $${total.toFixed(2)}`;
}

// 确保页面刷新后购物车数据不丢失
function saveCartItem(productId, productInfo) {
    let cartItems = JSON.parse(localStorage.getItem('cartItems')) || {};
    if (cartItems[productId]) {
        cartItems[productId].quantity += productInfo.quantity;
    } else {
        cartItems[productId] = productInfo;
    }
    localStorage.setItem('cartItems', JSON.stringify(cartItems));
}

function removeCartItem(productId) {
    let cartItems = JSON.parse(localStorage.getItem('cartItems')) || {};
    delete cartItems[productId];
    localStorage.setItem('cartItems', JSON.stringify(cartItems));
}

// 在页面加载时，从localStorage中恢复购物车数据。
document.addEventListener('DOMContentLoaded', function () {
    const cartItems = JSON.parse(localStorage.getItem('cartItems')) || {};
    for (const productId in cartItems) {
        const productInfo = cartItems[productId];
        const cartBox = document.createElement('div');
        cartBox.classList.add('box');

        cartBox.innerHTML = `
            <span class="fas fa-times cancel-btn"></span> <!-- 取消按钮 -->
            <img src="${productInfo.image}" alt="">
            <div class="content">
                <h3>${productInfo.name}</h3>
                <span class="quantity">${productInfo.quantity}</span>
                <span class="multiply">×</span>
                <span class="price">${productInfo.price}</span>
            </div>
        `;

        // 将新的购物车项添加到.shopping-cart容器中
        document.querySelector('.shopping-cart').appendChild(cartBox);

        // 为取消按钮添加事件监听器
        const cancelButton = cartBox.querySelector('.cancel-btn');
        cancelButton.addEventListener('click', function () {
            cartBox.remove(); // 移除购物车项
            updateCartTotal(); // 更新购物车总数
            removeCartItem(productId); // 从localStorage中移除购物车项
        });
    }

    // 更新购物车总数
    updateCartTotal();
});
